<?php
/**
 * 通用分页函数
 * @param	Number	$count			总记录数
 * @param	Number	$perpage		每页记录数
 * @param	Number	$page			当前页码
 * @param	String	$url			URL
 * @param	Array	$prop			给page容器传入class, id等属性，为了样式通用
 * @param	Number	$button_num		显示几个页码按钮
 * @return	String	$html
 * @author	Baiyu 2013-11-23
 */
function page($count, $perpage, $page, $url, $prop = array('class' => 'pagenavi center'), $button_num = 5, $total_at = 'left') {

	/* 开始page容器 */
	$html = '<div';
	foreach ($prop as $k => $v) {
		$html .= ' ' . $k . '="' . $v . '"';
	}
	$html .= '>' . "\n";

	//总数小于每页记录数不用分页
	if ($count <= $perpage) {
		return $html . "</div>\n";
	}

	/* 总记录条数 */
	$total_record = '<span>共' . $count . '条记录</span>' . "\n";
	$total_at == 'left' && $html .= $total_record;

	/* 上一页 */
	if ($page > 1) {
		$html .= '<a href="' . str_replace('#page#', $page - 1, $url) . '">上一页</a>' . "\n";
	}

	//重要参数计算
	$total_page = ceil($count / $perpage);
	//总页数
	$half_of_button_num = ceil($button_num / 2);
	//离首尾页多远就需要添加首尾按钮和点点了
	$need_dot = $total_page > $button_num + 2;
	//需要出现首尾按钮和点点，点点也点2个按钮位故加2
	$need_first_page = $need_dot && $page - 1 > $half_of_button_num;
	//需要首页按钮
	$need_last_page = $need_dot && $total_page - $page > $half_of_button_num;
	//需要尾页按钮
	$end_page = $need_last_page ? $page + $half_of_button_num - 1 : $total_page;
	//页码按钮结束页
	$start_page = $need_first_page ? ($need_last_page ? $page - $half_of_button_num + 1 : $end_page - $button_num) : 1;
	//页码按钮开始页

	/* 首页 */
	if ($need_first_page) {
		$html .= '<a href="' . str_replace('#page#', 1, $url) . '">1</a><span>...</span>' . "\n";
	}

	/* 页码按钮 */
	$for_length = $need_dot ? ($button_num + 2 - intval($need_first_page) - intval($need_last_page)) : $total_page;
	//无首尾页时可多放两个页码按钮且按钮总数等于总页码
	for ($i = 0; $i < $for_length; $i++) {
		$temp_page = $start_page + $i;
		$html .= ('<a' . ($temp_page == $page ? ' class="current"' : '') . ' href="' . str_replace('#page#', $temp_page, $url) . '">' . $temp_page . '</a>' . "\n");
	}

	/* 尾页 */
	if ($need_last_page) {
		$html .= '<span>...</span><a href="' . str_replace('#page#', $total_page, $url) . '">' . $total_page . '</a>' . "\n";
	}

	/* 下一页 */
	if ($page < $total_page) {
		$html .= '<a href="' . str_replace('#page#', $page + 1, $url) . '">下一页</a>' . "\n";
	}

	$total_at != 'left' && $html .= $total_record;

	/* 结束page容器 */
	$html .= '</div>' . "\n";

	return $html;
}
